import { ref, watch, computed } from "vue";
import { defineStore } from "pinia";
import { store } from "../index";
import { useSystemStoreHook } from "./system";
import { ElMessageBox } from "element-plus";

const useGradeStore = defineStore("grade", () => {
  const dataset = ref();

  const systemStore = useSystemStoreHook();
  const tables = computed(() => {
    return systemStore.tableConfigs.map((tbConf) => {
      const tableName = tbConf.name;
      let calc = 0;
      let rows: string[] = [];
      let cols: string[] = [];
      for (let i = 0; i < systemStore.grades.length; i++) {
        const grade = systemStore.grades[i];
        if (grade.gradeName === tbConf.row) {
          rows = grade.options;
          calc += 1;
        }
        if (grade.gradeName === tbConf.col) {
          cols = grade.options;
          calc += 1;
        }
      }
      rows = [...rows, "偏档", "合计"];
      if (calc !== 2) {
        ElMessageBox.confirm(
          `配置文件存在异常，请联系管理员解决：统计表初始化时发生错误，列查无${tbConf.col}或行查无${tbConf.row}`,
          { type: "warning", showCancelButton: false }
        );
      }
      const firstCeil = `${tbConf.row}\\${tbConf.col}`;
      return {
        rowName: tbConf.row,
        colName: tbConf.col,
        tableName,
        rows,
        cols: [firstCeil, ...cols, "偏档", "合计"]
      };
    });
  });

  watch(tables, tableDataUpdate, { immediate: true });

  function tableDataUpdate() {
    const _dataset = tables.value.map((table) => {
      const firstCeil = table.cols[0];
      const data = table.rows.map((r) => {
        const item = {};
        item[firstCeil] = r;
        return item;
      });
      return { ...table, data };
    });
    dataset.value = _dataset;
  }

  return {
    dataset,
    tableDataUpdate
  };
});

export function useGradeStoreHook() {
  return useGradeStore(store);
}
